﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;




using System.Runtime.InteropServices;//为   [DllImport("kernel32.dll")]写法提供支持
namespace EasyM1
{
    public partial class Form1 : Form
    {
        ///-----------DIY------------///
        [DllImport("kernel32.dll")]
        static extern void Sleep(int dwMilliseconds);

        [DllImport("hfrdapi.dll")]
        static extern int Sys_Open(ref IntPtr device,
                            UInt32 index,
                            UInt16 vid,
                            UInt16 pid);

        [DllImport("hfrdapi.dll")]
        static extern bool Sys_IsOpen(IntPtr device);

        [DllImport("hfrdapi.dll")]
        static extern int Sys_Close(ref IntPtr device);

        [DllImport("hfrdapi.dll")]
        static extern int Sys_SetBuzzer(IntPtr device, byte msec);

        [DllImport("hfrdapi.dll")]
        static extern int Sys_SetAntenna(IntPtr device, byte mode);

        [DllImport("hfrdapi.dll")]
        static extern int Sys_InitType(IntPtr device, byte type);

        //-----------------------------------M1--------------//
        [DllImport("hfrdapi.dll")]
        static extern int TyA_Request(IntPtr device, byte mode, ref UInt16 pTagType);

        [DllImport("hfrdapi.dll")]
        static extern int TyA_Anticollision(IntPtr device,
                                            byte bcnt,
                                            byte[] pSnr,
                                            ref byte pLen);

        [DllImport("hfrdapi.dll")]
        static extern int TyA_Select(IntPtr device,
                                     byte[] pSnr,
                                     byte snrLen,
                                     ref byte pSak);




        [DllImport("hfrdapi.dll")]
        static extern int TyA_CS_Authentication2(IntPtr device,
                                         byte mode,
                                         byte block,
                                         byte[] pKey);

        [DllImport("hfrdapi.dll")]
        static extern int TyA_CS_Read(IntPtr device,
                                      byte block,
                                      byte[] pData,
                                      ref byte pLen);

        [DllImport("hfrdapi.dll")]
        static extern int TyA_CS_Write(IntPtr device, byte block, byte[] pData);


        [DllImport("hfrdapi.dll")]
        static extern int TyA_UID_Write(IntPtr device, byte[] pData);

        ///身份证
        [DllImport("hfrdapi.dll")]//寻卡
        static extern int TyB_SGIDC_RequestAttrib(IntPtr device, byte mode, byte[] pData, byte[] pMsgLg);

        [DllImport("hfrdapi.dll")]//读UID
        static extern int TyB_SGIDC_GetUid(IntPtr device, byte[] pUid, byte[] pLen);







        IntPtr g_hDevice = (IntPtr)(-1); //g_hDevice must init as -1
        ///-----------DIY------------///
        public Form1()
        {
            InitializeComponent();
            comboBox1.Text = "0";
            comboBox2.Text = "0";
            radioButton2.Checked = true;
        }

//复位读卡器
        private void button3_Click(object sender, EventArgs e)
        {
            int status;
            string strError;
            unsafe
            {
                //NO.1:Check whether the reader is connected or not
                if (true == Sys_IsOpen(g_hDevice))
                {
                    //If the reader is already open , close it firstly
                    status = Sys_Close(ref g_hDevice);
                    if (0 != status)
                    {
                        strError = "Sys_Close failed !";
                        MessageBox.Show(strError, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }


                //Connect
                status = Sys_Open(ref g_hDevice, 0, 0x0416, 0x8020);
                if (0 != status)
                {
                    strError = "Sys_Open failed !";
                    MessageBox.Show(strError, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }


                //============= Init the reader before operating the card ============
                //NO.2:Close antenna of the reader
                status = Sys_SetAntenna(g_hDevice, 0);
                if (0 != status)
                {
                    strError = "Sys_SetAntenna failed !";
                    MessageBox.Show(strError, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                Sleep(5); //Appropriate delay after Sys_SetAntenna operating 

                //Set the reader's working mode
                status = Sys_InitType(g_hDevice, (byte)'A');
                if (0 != status)
                {
                    strError = "Sys_InitType failed !";
                    MessageBox.Show(strError, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                Sleep(5);

                //Open antenna of the reader
                status = Sys_SetAntenna(g_hDevice, 1);
                if (0 != status)
                {
                    strError = "Sys_SetAntenna failed !";
                    MessageBox.Show(strError, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                Sleep(5); //Appropriate delay after Sys_SetAntenna operating


                //============================ Success Tips ==========================
                //NO.3:Beep 200 ms
                status = Sys_SetBuzzer(g_hDevice, 20);
                if (0 != status)
                {
                    strError = "Sys_SetBuzzer failed !";
                    MessageBox.Show(strError, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
        }
        //DIY函数 把TEXT-->HEX
        public static byte GetHexBitsValue(byte ch)
        {
            byte sz = 0;
            if (ch <= '9' && ch >= '0')
                sz = (byte)(ch - 0x30);
            if (ch <= 'F' && ch >= 'A')
                sz = (byte)(ch - 0x37);
            if (ch <= 'f' && ch >= 'a')
                sz = (byte)(ch - 0x57);

            return sz;
        }
        //DIY函数 把TEXT-->HEX
        public static byte[] ToDigitsBytes(string theHex)
        {
            byte[] bytes = new byte[theHex.Length / 2 + (((theHex.Length % 2) > 0) ? 1 : 0)];
            for (int i = 0; i < bytes.Length; i++)
            {
                char lowbits = theHex[i * 2];
                char highbits;

                if ((i * 2 + 1) < theHex.Length)
                    highbits = theHex[i * 2 + 1];
                else
                    highbits = '0';

                int a = (int)GetHexBitsValue((byte)lowbits);
                int b = (int)GetHexBitsValue((byte)highbits);
                bytes[i] = (byte)((a << 4) + b);
            }

            return bytes;
        }

        ///---------下面------///
                #region byteHEX
        /// <summary>
        /// 单个字节转字字符.
        /// </summary>
        /// <param name="ib">字节.</param>
        /// <returns>转换好的字符.</returns>
        public static String byteHEX(Byte ib)
        {
            String _str = String.Empty;
            try
            {
                char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
                'B', 'C', 'D', 'E', 'F' };
                char[] ob = new char[2];
                ob[0] = Digit[(ib >> 4) & 0X0F];
                ob[1] = Digit[ib & 0X0F];
                _str = new String(ob);
            }
            catch (Exception)
            {
                new Exception("对不起有错。");
            }
            return _str;

        }
        #endregion

        public static string ToHexString(byte[] bytes)
        {
            String hexString = String.Empty;
            for (int i = 0; i < bytes.Length; i++)
                hexString += byteHEX(bytes[i]);

            return hexString;
        }
        ///---上面--///
//读卡操作
        private void button1_Click(object sender, EventArgs e)
        {
            int status;
            byte mode = 0x60;//默认Akey
            byte secnr = 0x00;//默认0扇区
            byte number = 0x00;//默认块
            byte[] dataBuffer = new byte[256];
            button4.PerformClick();//https://blog.csdn.net/qq_40182225/article/details/78711796
             // GONGJINHUA();
             //Check whether the reader is connected or not
            if (true != Sys_IsOpen(g_hDevice))
            {
                MessageBox.Show("Not connect to device !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            textBox1.Text = "";//清除显示框

            //准备参数1--ABKEY
            if (radioButton1.Checked)//如果B点击了就是Bkey
                mode = 0x61; //Bkey
            else
                mode = 0x60; //Akey

            //准备参数2--扇区
            //secnr = Convert.ToByte(comboBox1.SelectedItem.ToString());//只能下拉选择 不能自己键入 如果不拉 就死机
            secnr = Convert.ToByte(comboBox1.Text);
            //准备参数3--块儿
            //number = Convert.ToByte(comboBox2.SelectedItem.ToString());
            number = Convert.ToByte(comboBox2.Text);
            //准备参数4--秘钥
            byte[] bytesKey = ToDigitsBytes(textBox3.Text);//用到DIY函数 把TEXT-->HEX

            Sleep(5);
            //-------------------------------dev-------A/BKEY-------扇区--------key
            status = TyA_CS_Authentication2(g_hDevice, mode, (byte)(secnr * 4), bytesKey);//认证
            if (status != 0)
            {
                MessageBox.Show("TyA_CS_Authentication2 failed !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            byte cLen = 0;
            status = TyA_CS_Read(g_hDevice, (byte)((secnr * 4) + number), dataBuffer, ref cLen);

            if (status != 0 || cLen != 16)
            {
                MessageBox.Show("TyA_CS_Read failed !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            byte[] bytesData = new byte[16];
            for (int j = 0; j < bytesData.Length; j++)
                bytesData[j] = Marshal.ReadByte(dataBuffer, j);

            textBox1.Text = ToHexString(bytesData);//正常显示结果

            Sys_SetBuzzer(g_hDevice, 20);
        }



//写卡
        private void button2_Click(object sender, EventArgs e)
        {
            int status;
            byte mode = 0x60;
            byte secnr = 0x00;
            byte number;

            if (textBox2.Text.Length != 16 * 2)
            {
                MessageBox.Show("length err !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            button4.PerformClick();
            // GONGJINHUA();
            //Check whether the reader is connected or not
            if (true != Sys_IsOpen(g_hDevice))
            {
                MessageBox.Show("Not connect to device !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //准备参数1--ABKEY
            if (radioButton1.Checked)//如果B点击了就是Bkey
                mode = 0x61; //Bkey
            else
                mode = 0x60; //Akey


            //准备参数2--扇区
            //secnr = Convert.ToByte(comboBox1.SelectedItem.ToString());//只能下拉选择 不能自己键入 如果不拉 就死机
            secnr = Convert.ToByte(comboBox1.Text);

            //准备参数3--块儿
            //number = Convert.ToByte(comboBox2.SelectedItem.ToString());
            number = Convert.ToByte(comboBox2.Text);


            //准备参数4--秘钥
            byte[] bytesKey = ToDigitsBytes(textBox3.Text);//用到DIY函数 把TEXT-->HEX

            Sleep(5);
            //-------------------------------dev-------A/BKEY-------扇区--------key
            status = TyA_CS_Authentication2(g_hDevice, mode, (byte)(secnr * 4), bytesKey);
            if (status != 0)
            {
                MessageBox.Show("TyA_CS_Authentication2 failed !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            byte[] bytesBlock = ToDigitsBytes(textBox2.Text);
            if ((secnr + number) == 0)//支持 0 0的UID
            {
                status = TyA_UID_Write(g_hDevice,  bytesBlock);
            }                
            else
            {
                status = TyA_CS_Write(g_hDevice, (byte)((secnr * 4) + number), bytesBlock);
            }
            if (status != 0)
            {
                MessageBox.Show("TyA_CS_Write failed !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            Sys_SetBuzzer(g_hDevice, 20);

        }

        
        //连接卡  既然每次都要连接 也就没有button的意义了  它的意义是可以走流程获得UID显示 现在我也不显示了

        private void button4_Click(object sender, EventArgs e)
        {
            /*  这个也可以 下面的代码也可以 
             int status;
             byte mode = 0x52;
             ushort TagType = 0;
             byte bcnt = 0;
             byte[] dataBuffer = new byte[256];
             byte len = 255;
             byte sak = 0;

             //Check whether the reader is connected or not
             if (true != Sys_IsOpen(g_hDevice))
             {
                 MessageBox.Show("Not connect to device !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                 return;
             }

             for (int i = 0; i < 2; i++)
             {
                 status = TyA_Request(g_hDevice, mode, ref TagType);//搜寻所有的卡
                 if (status != 0)
                     continue;

                 status = TyA_Anticollision(g_hDevice, bcnt, dataBuffer, ref len);//返回卡的序列号
                 if (status != 0)
                     continue;

                 status = TyA_Select(g_hDevice, dataBuffer, len, ref sak);//锁定一张ISO14443-3 TYPE_A 卡
                 if (status != 0)
                     continue;

                 String m_cardNo = String.Empty;

                 for (int q = 0; q < len; q++)
                 {
                     m_cardNo += byteHEX(dataBuffer[q]);
                 }
                 textBox1.Text = m_cardNo;

                 break;
             }
             Sys_SetBuzzer(g_hDevice, 20);
             */

            byte mode = 0x26;
            ushort TagType = 0;
            int status;
            byte bcnt = 0;
            byte[] dataBuffer = new byte[256];
            byte len = 255;
            byte sak = 0;

            //Check whether the reader is connected or not
            if (true != Sys_IsOpen(g_hDevice))
            {
                MessageBox.Show("###Not connect to device !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            status = TyA_Request(g_hDevice, mode, ref TagType);//搜寻所有的卡
            if (status != 0)
            {
                MessageBox.Show("TyA_Request failed !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            String TagType_string = String.Empty;
            byte TagType_hightu8 =(byte) ((TagType & 0XFF00)>>8);
            byte TagType_lowu8 =  (byte) ( TagType & 0X00FF);
            TagType_string += byteHEX(TagType_hightu8);
            TagType_string += byteHEX(TagType_lowu8);
            status = TyA_Anticollision(g_hDevice, bcnt, dataBuffer, ref len);//返回卡的序列号
            if (status != 0)
            {
                MessageBox.Show("TyA_Anticollision failed !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            status = TyA_Select(g_hDevice, dataBuffer, len, ref sak);//锁定一张ISO14443-3 TYPE_A 卡
            if (status != 0)
            {
                MessageBox.Show("TyA_Select failed !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            String sak_string = String.Empty;
            sak_string += byteHEX(sak);


            String m_cardNo = String.Empty;

            for (int q = 0; q < len; q++)
            {
                m_cardNo += byteHEX(dataBuffer[q]);
            }
            textBox4.Text = m_cardNo; //GONGJINHUA 暂时不显示了   发现：每次读写 都要开始掉这个函数
            textBox5.Text = TagType_string; //GONGJINHUA 暂时不显示了   发现：每次读写 都要开始掉这个函数
            textBox6.Text = sak_string; //GONGJINHUA 暂时不显示了   发现：每次读写 都要开始掉这个函数
        }

        private void button5_Click(object sender, EventArgs e)
        {
            int status = 0;

            if (true != Sys_IsOpen(g_hDevice))
            {
                MessageBox.Show("Not connect to device !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            status = Sys_SetAntenna(g_hDevice, 0);
            Sleep(5); //Appropriate delay after Sys_SetAntenna operating 
            status = Sys_InitType(g_hDevice, (byte)'B');
            Sleep(5);
            status = Sys_SetAntenna(g_hDevice, 1);





            textBox1.Text = "";//清除显示框
            textBox2.Text = "";

            byte[] backdataBuffer = new byte[20];
            byte[] backdatalen = new byte[1];
            status = TyB_SGIDC_RequestAttrib(g_hDevice, 1, backdataBuffer, backdatalen);
            if (0 != status)//寻卡失败
            {
                textBox1.Text = status.ToString();
                return;
            }
           

            status = TyB_SGIDC_GetUid(g_hDevice, backdataBuffer, backdatalen);
            if (0 != status)//读卡失败
            {
                textBox1.Text = status.ToString();
                return;
            }
            ///////////////////获得string/////////////截取前面的9位////////HEX*2/////
            textBox1.Text = ToHexString(backdataBuffer).Substring(0, backdatalen[0]*2);
        }
    }
}
